<template>
  <div>
    <el-form :rules="rules"  v-loading="loading" ref="formLogin" :model="loginform" class="loginCont">
      <h3 class="lofinTitle">系统登录</h3>
      <el-form-item prop="username">
        <el-input type="text" prefix-icon="el-icon-user-solid" v-model="loginform.username" placeholder="请输入用户名"></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input type="password" prefix-icon="el-icon-lock" v-model="loginform.password" placeholder="请输入密码" show-password></el-input>
      </el-form-item>
      <el-form-item prop="code" >
        <el-input type="text" v-model="loginform.code" placeholder="请输入验证码" style="width: 220px; margin-right: 5px"></el-input>
        <div @click="changeCode()">
        <Sidentify style="float: right ;margin-top: -39px" :identifyCode="identifyCode" ></Sidentify>
        </div>
      </el-form-item>
<!--      <img :src="captchaUrl">-->
<!--      <el-checkbox v-model="checkbox" class="loginRemember">记住我</el-checkbox>-->
      <el-button type="primary" style="width: 100%" @click="submitLogin">登录</el-button>
      <div class="register" @click="registerbutton">--注册--</div>
    </el-form>
  </div>
</template>

<script>
import Sidentify from "@/components/SIdentify";//引入图片验证码
import {activRouter} from "@/utils/permission";
import {mapMutations} from 'vuex';

export default {
  name: "Login",
  components: {
    Sidentify
  },
  data() {
    return {
      captchaUrl:'',
      loginform:{
        username:"",
        password:'',
        code:''
      },
      checkbox:true,
      rules: {
        username: [{required: true, message: '请输入用户名', trigger: 'blur'}],
        password: [{required: true, message: '请输入密码', trigger: 'blur'}],
        code: [{required: true, message: '请输入验证码', trigger: 'blur'}],
      },
      loading:false,
      // 验证码初始值
      identifyCode: 'm6a8',// 这个就是随机生成的验证码
      // 验证码的随机取值范围
      identifyCodes: '123456789abcdefghjkmnpqrstuvwxyz',

    }
  },
  mounted() {
    // 刷新页面就生成随机验证码
    this.identifyCode = ''
    this.makeCode(this.identifyCodes, 4)

  },
    methods :{
      ...mapMutations(['setToken']),
      submitLogin(){

        this.$refs.formLogin.validate((valid) => {

          if (valid) {
            if (this.identifyCode === this.loginform.code){
              console.log("验证码正确")
                this.loading=true;
                this.$axios({
                  method:'post',
                  url:'/api/user/selectAll',
                  data:{
                    username : this.loginform.username,
                    password : this.loginform.password,
                    code : this.loginform.code,
                  }
                  // eslint-disable-next-line no-unused-vars
                }).then((resp) =>{

                  if (resp.data.success){

                    this.loading=false;
                    this.$message({message: resp.data.msg, type: 'success'});
                    sessionStorage.setItem("user",JSON.stringify(resp.data));//缓存用户信息
                    // const permissions = resp.data.data.permissions;
                    //登录成功之后更新信息
                    activRouter()
                    this.setToken({token: resp.data.token});    //store中的为token赋值方法
                    console.log(resp);
                    this.$router.replace('/home');//replace 可禁止返回上个页面
                  }else {
                    console.log(resp);
                    this.loading=false;
                    // this.$message({message: resp.data.msg, type: 'success'});
                    this.$message.error({message: resp.data.msg});
                  }

                }).catch((error) =>{
                  console.log(error);   //请求失败返回的数据
                  this.loading=false;
                  alert("登录异常")

                })
            }else {
              this.changeCode();// 改变验证码
              this.$message.error('验证码错误');
            }
          } else {
            console.log('error submit!!');
            this.$message.error('请输入所有字段');
            return false;
          }
        });
      },
      registerbutton(){
        //跳转到注册页面
        this.$router.push('/register');
      },
      // 点击验证码刷新验证码
      changeCode() {
        this.identifyCode = ''
        this.makeCode(this.identifyCodes, 4)
      },
      // 生成一个随机整数  randomNum(0, 10) 0 到 10 的随机整数， 包含 0 和 10
      randomNum(min, max) {
        max = max + 1
        return Math.floor(Math.random() * (max - min) + min)
      },
      // 随机生成验证码字符串
      makeCode(data, len) {
        for (let i = 0; i < len; i++) {
          this.identifyCode += data[this.randomNum(0, data.length - 1)]
        }
      }

    }
}
</script>

<style scoped>
.loginCont{
  border-radius: 15px;
  background-clip: padding-box;
  margin: 180px auto;
  width: 350px;
  padding: 15px 35px 15px 35px;
  background: #fff;
  border: 1px solid #eaeaea;
  box-shadow: 0 0 25px #cac6c6;
}
.lofinTitle{
  margin: 8px auto 40px auto;
  text-align: center;
}
.register{
  margin-top: 25px;
  font-size: 14px;
  text-align: center;
}
.loginRemember{
  float: left;
}
</style>
